#include"ThreadEnumeratorImpl_Win.h"
#include "HandleWraperImpl_Win.h"
#include "tools/helpMacros.h"
#include SD_TL_PLATFORM_IMPL_INC( tools,HandleWraper )
#include "WinExpection.h"

#include <TlHelp32.h>

using namespace sd::tools;
using namespace sd::tools::win;
using namespace sd::tools::thread_enumerator::impl;


void ProcessThreadEnumeratorImpl::openProcess( int processId )
{
	processID_ = processId?processId:GetCurrentProcessId();
	reload();
}
void ProcessThreadEnumeratorImpl::attachProcess( const HHANDLE& handle )
{
	processID_ = GetProcessId( handle.impl() );
	reload();
}


void ProcessThreadEnumeratorImpl::reload()
{
	HHANDLE snapshotHandle = HHANDLE(CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ));

	threads_.clear();

	if( !snapshotHandle )
		throw WinImplException( "Snapshot dont created" );
	
	THREADENTRY32 thread_entry;

	thread_entry.dwSize = sizeof(THREADENTRY32);

	if( !Thread32First( snapshotHandle.impl(), &thread_entry ) )
	{
		throw WinImplException( "Thread don't enumerated" );
	}

	int result = 0;

	do
	{
		if( thread_entry.th32OwnerProcessID == processID_ )
		{
			threads_.push_back( thread_entry.th32ThreadID  );
		}
	}
	while( Thread32Next( snapshotHandle.impl(), &thread_entry ) );
}